package Loginc

import (
	"baize/app/Middleware/Jwtc"
	"baize/app/Models"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
)

type ReqUserInfo struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

func Login(c *gin.Context) {
	// username := c.Query("username")
	// password := c.Query("password")
	reqBody, _ := io.ReadAll(c.Request.Body)
	// log.Println("method", c.Request.Method)
	// log.Println("body", string(reqBody))
	// log.Println("clientIP", c.Request.RemoteAddr)
	// log.Println("url", c.Request.RequestURI)
	var m ReqUserInfo
	err := json.Unmarshal(reqBody, &m) // 反序列化
	if err != nil {
		log.Println(err)
	}

	var json_users Models.Users

	if err != nil {
		log.Printf("mysql connect error %v", err)
	}

	user, err := json_users.FindUser(m.Username)
	if err != nil {
		log.Println(err)
		c.JSON(404, gin.H{
			"message": "用户不存在",
			"status":  false,
			"data":    fmt.Sprintf("%v", err),
		})
		return
	}

	// log.Printf("%v", userData)
	sign, err := Jwtc.Sign(user.Username)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
	}
	c.JSON(http.StatusOK, gin.H{
		"access_token": sign,
	})

}

func Register(c *gin.Context) {
	// reqBody, _ := io.ReadAll(c.Request.Body)
	// var m ReqUserInfo
	// err := json.Unmarshal(reqBody, &m) // 反序列化
	// if err != nil {
	// 	log.Println(err)
	// }
	var json Models.Users    //  定义json 变量 数据结构类型 为 Models.Users
	err := c.BindJSON(&json) //  获取前台传过来的 json 数据

	if err != nil {
		log.Println(err)
	}

	var validate = validator.New()
	errs := validate.Struct(json)
	if errs != nil {
		log.Println(errs.Error())
		c.JSON(400, gin.H{
			"message": "注册用户失败",
			"status":  false,
			"data":    fmt.Sprintf("%v", errs),
		})
		return
	}

	id, err := json.Insert()
	if err != nil {
		log.Printf("mysql connect error %v", err)
		c.JSON(400, gin.H{
			"message": "注册用户失败",
			"status":  false,
			"data":    fmt.Sprintf("%v", err),
		})
		return
	}

	var data *Models.CreateUsersResponse = new(Models.CreateUsersResponse)
	data.ID = id
	data.Name = json.Name
	data.Username = json.Username
	data.Mobile = json.Mobile
	data.Email = json.Email
	data.CreatedAt = json.CreatedAt
	data.UpdatedAt = json.UpdatedAt

	c.JSON(http.StatusOK, gin.H{
		"message": "注册用户成功",
		"status":  true,
		"data":    data,
	})
}
